import pymysql

from utils.read_yaml import yaml_config
from utils.logger import log


class MySQLUtil():
    # 初始化
    def __init__(self):

        self.application_config = yaml_config.read_application_config("application.yaml")
        self.host = self.application_config['dbconfig']['host']
        self.port = self.application_config['dbconfig']['port']
        self.user = self.application_config['dbconfig']['user']
        self.pwd = self.application_config['dbconfig']['pwd']
        self.dbName = self.application_config['dbconfig']['dbname']

    def connect(self):
        try:
            self.db = pymysql.connect(host=self.host, port=int(self.port), user=self.user, passwd=self.pwd,
                                      database=self.dbName, use_unicode=True, charset='utf8')
            self.cursor = self.db.cursor()
            print(self.db)
        except Exception as e:
            log.error(e)

    # 关闭数据库连接
    def close(self):
        try:
            self.cursor.close()
            self.db.close()
        except Exception as e:
            log.error(e)

    # 查询操作，查询单条数据
    def get_one(self, sql):
        # res = None
        try:
            self.connect()
            self.cursor.execute(sql)
            res = self.cursor.fetchone()
            self.close()
        except Exception as e:
            res = None
            log.error(e)
        return res

    # 查询操作，查询多条数据
    def get_all(self, sql):
        try:
            self.connect()
            self.cursor.execute(sql)
            res = self.cursor.fetchall()
            self.close()
        except Exception as e:
            res = ()
            log.error(e)
        return res

    # 数据库插入、更新、删除操作
    def insert(self, sql):
        return self.__edit(sql)

    def update(self, sql):
        return self.__edit(sql)

    def delete(self, sql):
        return self.__edit(sql)

    def __edit(self, sql):
        try:
            self.connect()
            count = self.cursor.execute(sql)
            self.db.commit()
            self.close()
        except Exception as e:
            self.db.rollback()
            count = 0
            log.error(e)
        return count


if __name__ == '__main__':
    mysql = MySQLUtil()
